<template>
  <a-card :bordered="false" :bodyStyle="{ padding: '24px 0', height: '100%' }">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="搜索学员:">
              <a-input v-model="keywords" placeholder="搜索学员/手机号(回车搜索)" style="width:80%;"
                @pressEnter="$refs.table.refresh(true)">
                <a-tooltip slot="suffix" title="搜索学员/手机号">
                  <a-icon type="search" style="color:rgba(0,0,0,.45)" @click="$refs.table.refresh(true)" />
                </a-tooltip>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="结业时间">
              <a-range-picker @change="onChange" style="width:80%;" />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="标签">
              <a-select mode="multiple" placeholder="请选择标签" style="width:80%;" v-model="queryParam.label_id">
                <a-select-option v-for="(item, index) in tagSelect" :key="index"
                  :value="item.id">{{ item.content }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <template v-if="advanced">
            <a-col :md="8" :sm="24">
              <a-form-item label="跟进人:">
                <a-select v-model="queryParam.user_id" style="width:80%;" placeholder="请选择跟进人" allowClear>
                  <a-select-option v-for="(item, index) in userList" :key="index"
                    :value="item.id">{{ item.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="学管师:">
                <a-select v-model="queryParam.academic_supervisor" style="width:80%;" placeholder="请选择学管师" allowClear>
                  <a-select-option v-for="(item, index) in userList" :key="index"
                    :value="item.id">{{ item.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </template>
        </a-row>
      </a-form>
    </div>
    <a style="cursor:pointer" v-if="advanced" @click="more" id="moreButton">
      收起
      <a-icon type="up"></a-icon>
    </a>
    <a style="cursor:pointer" v-if="!advanced" @click="more" id="moreButton">
      展开
      <a-icon type="down"></a-icon>
    </a>
    <div class="table-operator">
      <a-button type="primary" @click="$refs.followUp.showVisible()">今日待跟进({{ followUpCount.unComplete || '0' }})</a-button>
      <!-- <a-button type="primary" style="margin-left:10px;">批量提醒</a-button> -->
      <a-button :disabled="selectedRowKeys.length == 0" @click="showUser(selectedRows)"
        style="margin-left:10px;">批量分配跟进人</a-button>
      <a-button :disabled="selectedRowKeys.length == 0" @click="showManager(selectedRows)"
        style="margin-left:10px;">批量分配学管师</a-button>
    </div>
    <!-- <a-alert type="warning" message="预警值： 剩余课时≤7课时 或 剩余天数≤10天" banner class="expand_warning" /> -->
    <s-table ref="table" :columns="columns" :data="loadData" :scroll="{ x: 1800 }" class="user_management_table"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" style="margin-top:20px;"
      :pagination="pagination">
      <span slot="name" slot-scope="text,record">
        <a @click="nowClick(record)">{{ record.name }}</a>
        <a-icon type="man" v-if="record.sex == 1" style="color:#1890ff;margin-left:5px;" />
        <a-icon type="woman" v-if="record.sex == 2" style="color:#eb2f96;margin-left:5px;" />
      </span>
      <span slot="age" slot-scope="text,record">{{ record.age || record.birthday }}</span>
      <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
      <span slot="action" slot-scope="text,record">
        <a @click="signUp(record)">报名</a>
        <a-divider type="vertical" />
        <a @click="changeStudentType(record)">转为潜在</a>
      </span>
    </s-table>
    <user-modal ref="user" @reload="$refs.table.refresh()"></user-modal>
    <user-modal-manager ref="manager" @reload="$refs.table.refresh()"></user-modal-manager>
    <create-form ref="createModal" @ok="handleOk" />
    <follow-up-table-modal ref="followUp" :studentFileExpand="2"></follow-up-table-modal>
    <!-- <step-by-step-modal ref="modal" @ok="handleOk" /> -->
    <div class="ant-card" style="margin-top: 30px;padding: 30px;">
      <h2>历史学员</h2>
      <div style="display: flex; justify-content: space-around;">
        <div class="echart">
          <div class="echart" id="lineDemo" ref="chart" style="width: 1200px;height: 500px;"></div>
        </div>
      </div>
    </div>
  </a-card>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
// import StepByStepModal from '../../list/modules/StepByStepModal'
import CreateForm from '@/views/list/modules/CreateForm'
import { studentList, studentEdit } from '@/api/student'
import { accountList } from '@/api/account'
import { tagList } from '@/api/tag'
import userModal from '@/components/userModel/user'
import userModalManager from '@/components/userModel/manager'
import followUpTableModal from '@/components/followUpTable'
import { followUp } from '@/api/dashboardCount'
const statusMap = {
  0: {
    status: 'default',
    text: '关闭'
  },
  1: {
    status: 'processing',
    text: '运行中'
  },
  2: {
    status: 'success',
    text: '已上线'
  },
  3: {
    status: 'error',
    text: '异常'
  }
}

export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    userModal,
    userModalManager,
    followUpTableModal
    // StepByStepModal
  },
  data() {
    return {
      option: {
        title: {
          text: 'History students'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend: {
          data: ['测试课程1', '测试课程2', '测试课程3', '测试课程4', '测试课程5'],
          textStyle: {
            color: '#a1a1a1'
          }
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '测试课程1',
            type: 'line',
            stack: 'Total',
            areaStyle: {
              color: 'rgba(136, 155, 216)' // 单一颜色
            },
            lineStyle: {
              color: 'rgb(136, 155, 216)' // 线条颜色
            },
            emphasis: {
              focus: 'series'
            },
            data: [120, 132, 101, 134, 90, 230, 210]
          },
          {
            name: '测试课程2',
            type: 'line',
            stack: 'Total',
            areaStyle: {
              color: 'rgba(178, 220, 159)' // 单一颜色
            },
            lineStyle: {
              color: 'rgba(178, 220, 159)' // 单一颜色
            },
            emphasis: {
              focus: 'series'
            },
            data: [220, 182, 191, 234, 290, 330, 310]
          },
          {
            name: '测试课程3',
            type: 'line',
            stack: 'Total',
            areaStyle: {
              color: 'rgba(252, 217, 139)' // 单一颜色
            },
            lineStyle: {
              color: 'rgba(252, 217, 139)' // 单一颜色
            },
            emphasis: {
              focus: 'series'
            },
            data: [150, 232, 201, 154, 190, 330, 410]
          },
          {
            name: '测试课程4',
            type: 'line',
            stack: 'Total',
            areaStyle: {
              color: 'rgba(244,148, 148)' // 单一颜色
            },
            lineStyle: {
              color: 'rgba(244,148, 148)' // 单一颜色
            },
            emphasis: {
              focus: 'series'
            },
            data: [320, 332, 301, 334, 390, 330, 320]
          },
          {
            name: '测试课程5',
            type: 'line',
            stack: 'Total',
            label: {
              show: true,
              position: 'top'
            },
            areaStyle: {
              color: 'rgba(157, 211, 232)' // 单一颜色
            },
            lineStyle: {
              color: 'rgba(157, 211, 232)' // 单一颜色
            },
            emphasis: {
              focus: 'series'
            },
            data: [820, 932, 901, 934, 1290, 1330, 1320]
          }
        ]
      },
      pagination: {
        showTotal: total => `共${total}条数据`,
      },
      mdl: {},
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      keywords: null,
      tagSelect: [], //标签
      userList: [],
      queryParam: {
        type: 2,
        school_id: this.$store.state.user.school
      },
      queryParams: {
        user_type: 0,
        type: 1,
        school_id: this.$store.state.user.school
      },
      selectedRowKeys: [],
      selectedRows: [],
      // 表头
      columns: [
        {
          title: '学员姓名',
          dataIndex: 'name',
          width: 200,
          fixed: 'left',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '手机号码',
          fixed: 'left',
          width: 200,
          dataIndex: 'main_phone',
        },
        {
          title: '年龄',
          dataIndex: 'age',
          align: 'center', //
          // scopedSlots: { customRender: 'age' }
        },
        {
          title: '年级',
          dataIndex: 'grade',
        },
        {
          title: '创建时间',
          dataIndex: 'created_at',
        },
        {
          title: '结业时间',
          dataIndex: 'graduation_time',
        },
        {
          title: '最后就读课程',
          dataIndex: 'remainingClass',
        },
        {
          title: '跟进人',
          dataIndex: 'user_name',
        },
        {
          title: '学管师',
          dataIndex: 'academic_supervisor_name',
        },

        {
          title: '操作',
          //   width: '100px',
          dataIndex: 'action',
          fixed: 'right',
          align: 'right',
          ellipsis: true,
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        let postData = {}
        for (let key in this.queryParam) {
          if (this.queryParam[key]) {
            let nature = key
            postData[nature] = this.queryParam[key]
          }
        }
        return studentList(Object.assign(parameter, postData, { keywords: this.keywords || undefined })).then(res => {
          return res
        })
      },
      followUpCount: {
        unComplete: 0,
        complete: 0
      }
    }
  },
  watch: {
    queryParam: {
      handler(newName, oldName) {
        this.$refs.table.refresh()
      },
      //immediate:true代表如果在 wacth 里声明了obj之后，就会立即先去执行里面的handler方法，
      immediate: false,
      deep: true // 开启深度监听，默认是false
    },
    creat_visible(val) {
      if (val == false) {
        this.previewVisible = false
        this.previewImage = ''
        this.fileList = []
        this.visibleType = ''
        this.form = {
          content: '',
          time: ''
        }
        this.btnLoading = false
        this.time = undefined
      }
    },
  },
  created() {
    followUp(this.queryParams).then(res => {
      this.followUpCount.unComplete = res.unComplete
      this.followUpCount.complete = res.complete
    })
    this.conditionquery()
  },
  mounted() {
    const chartDom = document.getElementById('lineDemo')
    const myChart = this.$echarts.init(chartDom)
    myChart.clear()
    myChart.setOption(this.option)
  },
  methods: {
    handleButtonClick(e) {
      console.log('click', e)
    },
    handleMenuClick(e) {
      console.log('click', e)
    },
    //条件查询c
    conditionquery() {
      //标签
      tagList({ pageSize: 999999, school_id: this.$store.state.user.school })
        .then(res => {
          this.tagSelect = res.data
        })
        .catch(err => {
          this.$message.error(err.data.message || '获取标签数据失败，请刷新页面或稍后再试')
        })
      //跟进人
      accountList({ pageSize: 999999, school_id: this.$store.state.user.school })
        .then(res => {
          this.userList = res.data
        })
        .catch(err => {
          this.$message.error(err.data.message || '获取跟进人数据失败，请刷新页面或稍后再试')
        })
    },
    //结业时间
    onChange(date, dateString) {
      this.queryParam.last_start_time = dateString[0]
      this.queryParam.last_end_time = dateString[1]
      this.$refs.table.refresh()
    },
    nowClick(e) {
      this.$router.push({ name: 'student_Info', query: { id: e.id } })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    showUser(data) {
      let arr = []
      data.forEach(val => {
        arr.push(val.id)
      })
      this.$refs.user.showModal(arr)
    },
    showManager(data) {
      let arr = []
      data.forEach(val => {
        arr.push(val.id)
      })
      this.$refs.manager.showModal(arr)
    },
    handleEdit(record) {
      console.log(record)
    },
    handleSub(record) {
      if (record.status !== 0) {
        this.$message.info(`${record.no} 订阅成功`)
      } else {
        this.$message.error(`${record.no} 订阅失败，规则已关闭`)
      }
    },
    handleOk() {
      this.$refs.table.refresh()
    },

    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date())
      }
    },
    signUp(e) {
      this.$router.push({ name: 'apply', query: { id: e.id } })
    },
    changeStudentType(e) {
      let data = JSON.parse(JSON.stringify(e))
      data.type = 3
      console.log(data)
      data.age = !data.birthday ? 1 : this.getAge(data.birthday)
      studentEdit(data, data.id)
        .then(res => {
          this.$message.success('更改学员状态成功')
          this.$refs.table.refresh()
        })
        .catch(err => {
          this.$message.error(err.data.message || '更改学员状态失败~')
        })
    },
    getAge(strAge) {
      let birArr = strAge.split('-')
      let birYear = birArr[0]
      let birMonth = birArr[1]
      let birDay = birArr[2]

      d = new Date()
      let nowYear = d.getFullYear()
      let nowMonth = d.getMonth() + 1 //记得加1
      let nowDay = d.getDate()
      let returnAge

      if (birArr == null) {
        return false
      }
      let d = new Date(birYear, birMonth - 1, birDay)
      if (d.getFullYear() == birYear && d.getMonth() + 1 == birMonth && d.getDate() == birDay) {
        if (nowYear == birYear) {
          returnAge = 0 //
        } else {
          let ageDiff = nowYear - birYear //
          if (ageDiff > 0) {
            if (nowMonth == birMonth) {
              let dayDiff = nowDay - birDay //
              if (dayDiff < 0) {
                returnAge = ageDiff - 1
              } else {
                returnAge = ageDiff
              }
            } else {
              let monthDiff = nowMonth - birMonth //
              if (monthDiff < 0) {
                returnAge = ageDiff - 1
              } else {
                returnAge = ageDiff
              }
            }
          } else {
            return '出生日期晚于今天，数据有误' //返回-1 表示出生日期输入错误 晚于今天
          }
        }
        return returnAge
      } else {
        return '输入的日期格式错误！'
      }
    },
    more() {
      this.advanced = !this.advanced
    }
  }
}
</script>
<style lang="less" scoped>
.expand_warning {
  margin: 16px 0;
  background-color: #fff0e7;
  border-radius: 4px;
}

#moreButton {
  position: absolute;
  top: 34px;
  right: 20px;
}
</style>